const app = getApp()
import Toast from '../vant/toast/toast';
Page({
  data: {
    loading:true,
    showbar:false,
    banner: [],
    coupon:[],
    active:"new",
    page:0
  },
  //生命周期函数--监听页面加载
  onLoad: function (options){
    app.getParam(options);
    wx.setNavigationBarTitle({
      title: app.appname,
    })
    this.getAdwords();
    this.couponApi();
  },
  //下拉刷新
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    setTimeout(()=>{
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    },1500);
    this.setData({
      loading: true,
      page:0,
      coupon:[]
    });
    this.couponApi();
  },
  //下拉
  onReachBottom: function () {
    this.setData({
      loading: true,
    });
    this.couponApi();
  },
  //获取API
  getAdwords: function () {
    app.api().Get('api/v1/smartbc/index/adwords',{ids:'index'},(result) => {
      if (result.code == 200) {
        this.setData({
          banner:result.data.index
        })
      }
    })
  },
  //读取优惠券
  couponApi: function () {
    var coupon = this.data.coupon;
    if (this.data.loading) {
      var param = {
        page: this.data.page + 1,
        mode:this.data.active
      }
      app.api().Get('api/v1/smartbc/index/coupon',param,(result) => {
        if (result.code == 200) {
          for (let i in result.data) {
            coupon.push(result.data[i]);
          }
          this.setData({
            coupon: coupon,
          });
          this.data.page =  param.page;
        }
        this.setData({
          loading: false
        })
      })
    }
  },
  //领取优惠券
  onCoupon: function (e) {
    Toast.loading({message: '加载中'});
    setTimeout(() => {
      wx.hideLoading();
    },1000)
    var coupon_key = e.currentTarget.dataset.key;
    var coupon = this.data.coupon;
    app.api().Post('api/v1/smartbc/coupon/getCoupon',{id: e.currentTarget.id},(rel) => {
      Toast.success('领取成功');
      coupon[coupon_key]['is_get_coupon'] = 1;
      this.setData({
        coupon: coupon,
      })
    })
  },
  //查看优惠券规则
  reCoupon:function(e){
     wx.navigateTo({
       url:e.currentTarget.dataset.url,
       fail: (res) => {
         app.wxAlert('未找到页面')
       }
     })
  },
  //Tab切换
  onTabChange:function(event){
    this.setData({
      active: event.detail.name,
      loading: true,
      page:0,
      coupon:[]
    });
    this.couponApi();
  },
  //滚动
  onPageScroll(res){
    let scrollTop = res.scrollTop;
    this.setData({
      showbar: 150 <= scrollTop ?true :false
    })
  },
  //转发
  onShareAppMessage: function (res) {
    return {
      title: app.globalData.appConfig.shore_text,
      imageUrl: app.globalData.appConfig.shore_img,
      path: '/page/index?ucode='+app.globalData.ucode
    }
  }
})